﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System;

namespace TyMES.MidWare
{
    public class ExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger logger;
        private readonly IHostEnvironment env;

        public ExceptionFilter(ILogger<ExceptionFilter> logger, IHostEnvironment env)
        {
            this.logger = logger;
            this.env = env;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            Exception exception = context.Exception;
            logger.LogError(exception, "unhandledException occured!");
            string message;
            if (env.IsDevelopment())
            {
                //message = exception.Message;
                message = "服务器出现异常";
            }
            else
            {
                message = "服务器出现异常";
            }

            ObjectResult result = new ObjectResult(new { code = 500, message = message });
            result.StatusCode = 500;
            context.Result = result;
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
